import redis
from config import get_config

class RedisUtils:
    def __init__(self):
        try:
            settings = get_config()
            self.redis = redis.Redis(host=settings.REDIS_HOST, db=settings.REDIS_DB, password=settings.REDIS_PASSWORD, port=settings.REDIS_PORT)
        except Exception as e:
            print("Redis连接异常", str(e))
            self.redis = None
    # 设置值
    def set(self, key, content, expire=0):
        if self.redis == None:
            return None
        if expire > 0:
            return self.redis.set(key, content, ex=expire)
        else:
            return self.redis.set(key, content)
    # 获取值
    def get(self, key):
        if self.redis == None:
            return None
        return self.redis.get(key)
    # 设置值
    def hset(self, key, field, content, expire=0):
        if self.redis == None:
            return None
        if expire > 0:
            return self.redis.set(key, field, content, ex=expire)
        else:
            return self.redis.set(key, field, content)
    # 获取值
    def hget(self, key, field):
        if self.redis == None:
            return None
        return self.redis.hget(key, field)
    # 队列长度
    def length(self, key):
        if self.redis == None:
            return 0
        return self.redis.llen(key)  # 返回队列里面list内元素的数量
    # 入队
    def rpush(self, key, value):
        if self.redis == None:
            return False
        return self.redis.rpush(key, value)
        
    # 出队
    def lpop(self, key):
        if self.redis == None:
            return None
        return self.redis.lpop(key)
    # 删除
    def delete(self, key):
        if self.redis == None:
            return False
        self.redis.delete(key)
        return True
    # 获取Redis对象
    def getRedis(self):
        return self.redis
    # 添加到延迟队列
    def zadd(self, key, mapping):
        if self.redis == None:
            return False
        return self.redis.zadd(key, mapping=mapping)
    # 获取待执行的
    def zrangebyscore(self, key, mint, maxt):
        if self.redis == None:
            return []
        return self.redis.zrangebyscore(key, mint, maxt)
    # 删除一个元素
    def zrem(self, key, name):
        if self.redis == None:
            return False
        self.redis.zrem(key, name)
        return True

    # 关闭链接
    def close(self):
        if self.redis != None:
            self.redis.close()
    
def get_redis():
    redis = RedisUtils()
    try:
        yield redis
    finally:
        print("Close Redis")
        redis.close()
